#include "BufferTab.h"
#include "BufferView.h"
#include "utils/buffer.h"
#include <QStack>

BufferTab::BufferTab(QWidget *parent) :
    QTabWidget(parent)
{
    setAccessibleName(tr("Packet bytes"));
    setTabPosition(QTabWidget::South);
    setDocumentMode(true);
    setTabBarAutoHide(true);

    // Shrink down to a small but nonzero size in the main splitter.
    int one_em = fontMetrics().height();
    setMinimumSize(one_em, one_em);
}

void BufferTab::addTab(FERange range) {
    QString name = ((FEBuffer *)range.buffer)->name;
    BufferView * byte_view_text = new BufferView(range, this);
    byte_view_text->setAccessibleName(name);
    byte_view_text->setMonospaceFont(QFont("Consolas", 11));

    int idx = QTabWidget::addTab(byte_view_text, name);
    QTabWidget::setTabToolTip(idx, name);
}

void BufferTab::selectedChanged(FERange range)
{
    QStack<FERange> stack;
    FERange frame = range;
    while (frame.buffer) {
        stack.push(frame);
        frame.bit_offset = ((FEBuffer *)frame.buffer)->parent_bit_offset;
        frame.bit_len = ((FEBuffer *)frame.buffer)->parent_bit_len;
        frame.buffer = ((FEBuffer *)frame.buffer)->parent;
    }

    int tabs = count();
    int frames = stack.count();

    int index = 0;
    while (index < frames) {
        if (index < tabs) {
            dynamic_cast<BufferView *>(widget(index))->markRange(stack.pop());
        } else {
            addTab(stack.pop());
        }

        index++;
    }

    index = tabs - 1;
    while (index >= frames) {
        delete widget(index);
        removeTab(index);
        index--;
    }

    setCurrentIndex(frames - 1);
}
